package weixin.servlet;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import weixin.pojo.Message;
import weixin.pojo.TextMessage;
import weixin.util.InterfaceUtil;
import weixin.util.PojoUtil;

public class WeixinServlet extends HttpServlet {

	public static final String Token = "jeffrey";
	private static Logger logger = LoggerFactory.getLogger(WeixinServlet.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = -4571270943087154143L;

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Message inMsg = PojoUtil.parseMessage(request.getInputStream());
		if (inMsg != null) {
			TextMessage toMsg = new TextMessage();
			toMsg.setFromUserName(inMsg.getToUserName());
			toMsg.setCreateTime(new Date().getTime() + "");
			String fromUserName = inMsg.getFromUserName();
			toMsg.setToUserName(fromUserName);
			toMsg.setContent("Hello " + "  "
					+ InterfaceUtil.getUser(fromUserName).getNickname()
					+ ",Welcome to my space!");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(PojoUtil.transformMessage(toMsg));
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		logger.info("start developer authentication!");
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		logger.info("signature is: " + signature);
		logger.info("timestamp is: " + timestamp);
		logger.info("nonce is: " + nonce);
		if (signature != null && signature.length() > 0 && timestamp != null
				&& timestamp.length() > 0 && nonce != null
				&& nonce.length() > 0) {
			String[] tmpArr = { Token, timestamp, nonce };
			Arrays.sort(tmpArr);
			StringBuffer sb = new StringBuffer();
			for (String s : tmpArr) {
				sb.append(s);
			}
			String encryptStr = Encrypt(sb.toString());
			String echostr = request.getParameter("echostr");

			logger.info("Encrypt String is: " + encryptStr);
			logger.info("echostr is: " + echostr);

			if (encryptStr != null && encryptStr.equals(signature)) {
				if (echostr != null && echostr.length() > 0) {
					logger.info("developer authentication success!");
					response.getWriter().print(echostr);
				} else {
					logger.info("developer authentication failure!");
				}
			} else {
				logger.info("developer authentication failure!");
			}
		}
		logger.info("end developer authentication!");
	}

	public String Encrypt(String strSrc) {
		MessageDigest md = null;
		String strDes = null;
		byte[] bt = strSrc.getBytes();

		try {
			md = MessageDigest.getInstance("SHA-1");
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			logger.error("Invalid Encrypt algorithm.");
			e.printStackTrace();
			return null;
		}
		return strDes;
	}

	public String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
}
